import React, { useReducer } from 'react';
import { Input, Select, Checkbox, Tooltip } from 'antd';
import { useDeepCompareEffect } from 'ahooks';
import isPlainObject from 'lodash/isPlainObject';
import get from 'lodash/get';

import { OPERATORS } from '@/pages/Transformer/settings';
import NodePathSelect from '../NodePathSelect';
import styles from './styles.less';

const { Option } = Select;

const initialState = {
  value: {
    // lhsPath: [],
    op: 'eq',
  },
};

function reducer(state, action) {
  const { type, payload } = action;

  if (type === 'sync_props') {
    return {
      ...state,
      ...payload,
    };
  }

  if (type === 'change_value') {
    return {
      ...state,
      value: { ...state.value, ...payload },
    };
  }

  throw new Error();
}

function Expression({
  value,
  disabled = false,
  readOnly = false,
  onChange,
  mode = 'select',
  treeData,
}) {
  // const [state, setState] = useControllableValue(props);
  const [state, dispatch] = useReducer(reducer, initialState);

  useDeepCompareEffect(() => {
    if (isPlainObject(value) && Array.isArray(get(value, 'lhsPath'))) {
      dispatch({ type: 'sync_props', payload: { value } });
    }
  }, [value, dispatch]);

  return (
    <>
      <NodePathSelect
        treeData={treeData}
        mode={mode}
        value={state.value.lhsPath}
        onChange={value => {
          dispatch({ type: 'change_value', payload: { lhsPath: value } });
          onChange({ ...state.value, lhsPath: value });
        }}
        disabled={disabled}
        readOnly={readOnly}
        className={styles.path}
      />
      <Select
        value={state.value.op}
        onChange={value => {
          dispatch({ type: 'change_value', payload: { op: value } });
          onChange({ ...state.value, op: value });
        }}
        disabled={disabled}
        readOnly={readOnly}
        className={styles.op}
      >
        {OPERATORS.map(k => (
          <Option key={k.value} value={k.value} title={k.title}>
            {k.title}
          </Option>
        ))}
      </Select>
      {['is_not_empty', 'is_empty', 'is_not_blank', 'is_blank'].includes(state.value.op) ? null : (
        <Input
          value={get(state, 'value.rhs.stringValue')}
          onChange={e => {
            // let format;
            // // 猜测用户要的是`number`还是`string`
            // if (get(value, 'rhs') && ['string', 'number'].includes(format)) {
            //   format = typeof get(value, 'rhs');
            // } else {
            //   format = /^\d+$/.test(e.target.value) ? 'number' : 'string';
            // }

            // const newValue =
            //   format === 'string' ? String(e.target.value) : parseInt(e.target.value, 10);

            const rhs = {
              stringValue: e.target.value,
              isString:
                typeof get(state, 'value.rhs.isString') === 'boolean'
                  ? get(state, 'value.rhs.isString')
                  : true,
            };

            dispatch({
              type: 'change_value',
              payload: {
                rhs,
              },
            });
            onChange({
              ...state.value,
              rhs,
            });
          }}
          placeholder="值"
          disabled={disabled}
          readOnly={readOnly}
          className={styles.rhs}
          allowClear
          addonAfter={
            <Tooltip title="是否当成字符串处理">
              <Checkbox
                checked={
                  typeof get(state, 'value.rhs.isString') === 'boolean'
                    ? get(state, 'value.rhs.isString')
                    : true
                }
                onChange={e => {
                  const rhs = {
                    stringValue: get(state, 'value.rhs.stringValue') || '',
                    isString: e.target.checked,
                  };

                  dispatch({
                    type: 'change_value',
                    payload: {
                      rhs,
                    },
                  });

                  onChange({
                    ...state.value,
                    rhs,
                  });
                }}
              />
            </Tooltip>
          }
        />
      )}
    </>
  );
}

export default Expression;
